 <template>
  <!-- 页面-组织架构-职位管理-新建职位 -->
  <div>
    <Form :model="formInfo" ref="positonForm" :rules="rules" :label-width="80">
      <!-- 职位编码 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item :label="$t('module.orgManage.jobCode')" prop="code">
            <Input
              placeholder
              v-model="formInfo.code"
              :disabled="propsPosintionInfo.newOrEdit == 'edit'"
              :maxlength="30"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 职位名称 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item :label="$t('module.orgManage.jobName')" prop="name">
            <Input placeholder v-model="formInfo.name" :maxlength="100"></Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 职务 -->
      <Row :gutter="32" class="code-row-bg" align="middle">
        <Col span="24">
          <Form-item :label="$t('module.orgManage.position')" prop="jobName">
            <Input disabled v-model="formInfo.jobName">
              <Button
                type="primary"
                slot="append"
                class="select-btn"
                @click="selectPosition('org','new')"
              >{{ $t('module.orgManage.select') }}</Button>
            </Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 主管职位 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item prop="mainPostFlag" :label="$t('module.orgManage.supervisorJobs')">
            <RadioGroup v-model="formInfo.mainPostFlag" size="small">
              <Radio :label="1">{{this.$t("module.orgManage.yes")}}</Radio>
              <Radio :label="0">{{this.$t("module.orgManage.no")}}</Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <!-- 排序号 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item :label="$t('module.orgManage.sortId')" prop="sort">
            <InputNumber
              style="width:100%;"
              :min="0"
              :max="99"
              v-model="formInfo.sort"
              :placeholder="$t('module.orgManage.pleaseInput')"
            ></InputNumber>
          </Form-item>
        </Col>
      </Row>
      <!-- 状态 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item :label="$t('common.status')" prop="enabled">
            <RadioGroup v-model="formInfo.enabled">
              <Radio :label="1">{{ $t("common.valid") }}</Radio>
              <Radio :label="0">{{ $t("common.invalid") }}</Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <!-- 描述 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item :label="$t('module.orgManage.orgDesc')" prop="orgDesc">
            <Input
              placeholder
              type="textarea"
              :rows="4"
              :maxlength="1000"
              v-model="formInfo.positionDesc"
            ></Input>
          </Form-item>
        </Col>
      </Row>
    </Form>
    <form-create v-if="isShow" v-model="fcApi" :rule="ruleData" :option="option"></form-create>
    <!-- <form-create></form-create> -->
  </div>
</template>

<script>
import { addPosition, updatePosition } from "@/api/orgApi.js";
import locales from "../locales.js";
import { getDepartmentTemplateList, templateDetail } from "@/api/extendAttrApi.js";

import selectPosition from "./selectPosition.vue";

export default {
  mixins: [locales],
  components: {},
  props: {
    propsPosintionInfo: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    // 部门编码
    const validateOrgCode = (rule, value, callback) => {
      if (value != value.trim()) {
        callback(new Error(this.$t("module.orgManage.codeNoBalnk")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("module.orgManage.codeMaxFifty")));
      } else if (!new RegExp("^([a-zA-Z0-9_]|-|\\/|\\.)+$").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    // 部门名称
    const validateOrgName = (rule, value, callback) => {
      if (value != value.trim()) {
        callback(new Error(this.$t("module.orgManage.noBalnk")));
      } else if (value.length > 100) {
        callback(new Error(this.$t("module.orgManage.nameMaxFifty")));
      } else if (value.trim() == "") {
        callback(new Error(this.$t("module.orgManage.emptyName")));
      }
      callback();
    };
    // 职务
    const validateJobCode = (rule, value, callback) => {
      if (value.trim() == "") {
        callback(new Error(this.$t("module.orgManage.emptyPosition")));
      }
      callback();
    };
    // 部门描述
    const validateOrgDesc = (rule, value, callback) => {
      if (value != null && value != value.trim() && value.trim() === "") {
        callback(new Error(this.$t("module.orgManage.enterLegalDesc")));
      }
      if (value != null && value.length > 1000) {
        callback(new Error(this.$t("module.orgManage.descMaxTH")));
      }
      callback();
    };
    return {
      formInfo: {
        code: "", //职位编码
        name: "", //职位名称
        jobCode: "", //职务编码
        jobName: "", //职务名称
        mainPostFlag: 0, //是否主管职位
        sort: 1, //排序号
        positionDesc: "", //描述
        enabled: 1, //状态
        parentCode: "", //父职位编码或者部门编码
        positionId: ""
      },
      dapartTemplateList: [],
      isShow: false,
      isShowTemplate: true,
      ruleList: [],
      fcApi: null,
      // 字段规则
      rules: {
        code: [{ validator: validateOrgCode, trigger: "blur", required: true }],
        name: [{ validator: validateOrgName, trigger: "blur", required: true }],
        jobName: [{ validator: validateJobCode, trigger: "blur", required: true }],
        sort: [{ required: true }],
        positionDesc: [{ validator: validateOrgDesc, trigger: "blur" }]
      },
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.onOk();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  created: function() {
    if (this.propsPosintionInfo.newOrEdit == "edit") {
      this.$emit("SetTitle", this.$t("module.orgManage.editPosition"));
      const _orgInfo = this.propsPosintionInfo.row;
      this.formInfo = {
        code: _orgInfo.code,
        name: _orgInfo.name,
        jobCode: _orgInfo.jobCode,
        jobName: _orgInfo.jobName,
        mainPostFlag: parseInt(_orgInfo.mainPostFlag),
        sort: parseInt(_orgInfo.sort),
        positionDesc: _orgInfo.positionDesc,
        enabled: parseInt(_orgInfo.enabled)
      };
      this.ruleList = _orgInfo.attributeValue ? _orgInfo.attributeValue.template : [];
      this.isShow = true;
    } else {
      this.$emit("SetTitle", this.$t("module.orgManage.newPosition"));
    }

    this.$emit("SetPageWidth", 600);
    this.$emit("SetPageActions", this.actions);
    this.getDepartmentTemplate([1]);
  },
  computed: {
    extendedAttrTitle: function() {
      return this.$t("module.orgManage.extendedAttr");
    },
    ruleData() {
      return this.ruleList;
    },
    option() {
      return {
        resetBtn: false,
        submitBtn: false,
        form: {
          labelWidth: 100,
          size: "default"
        }
      };
    }
  },
  methods: {
    // 获取部门模板列表
    // 获取公司模板数据
    getDepartmentTemplate(statusList) {
      getDepartmentTemplateList(statusList).then(res => {
        if (res.data.length == 0) {
          this.isShowTemplate = false;
          return;
        }
        this.dapartTemplateList = res.data;
      });
    },
    // 新建职位
    addPosition() {
      this.formInfo.parentCode = this.propsPosintionInfo.parentCode;
      addPosition(this.formInfo)
        .then(data => {
          this.$message.success({
            content: this.$t("module.orgManage.addPositionSuccess"),
            duration: 3
          });
          this.modal = false;
          let params = {
            newOrEdit: "new"
          };
          this.$emit("Close", params);
        })
        .catch(data => {
          this.actions[0].loading = false;
        });
    },
    // 编辑职位
    updatePosition() {
      this.formInfo.id = this.propsPosintionInfo.row.id;
      updatePosition(this.formInfo)
        .then(data => {
          this.$message.success({
            content: this.$t("module.orgManage.editPositionSuccess"),
            duration: 3
          });
          this.modal = false;
          // this.$emit("Close", true);
          // 把数据传回页面
          let params = {
            newOrEdit: "edit"
          };
          this.$emit("Close", params);
        })
        .catch(data => {
          this.actions[0].loading = false;
        });
    },

    onOk() {
      this.formInfo.attributeValue = {
        template: this.ruleData
      };
      this.$refs["positonForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (this.propsPosintionInfo.newOrEdit == "edit") {
            this.updatePosition();
          } else {
            this.addPosition();
          }
        } else {
          this.$message.error(this.$t("common.formValidateFailed"));
        }
      });
    },
    // 选择职务     idx:org代表是在组织下新建根部门节点，dept代表是在根部门下新建子部门节点
    selectPosition(idx, newOrEdit, row) {
      this.deptNodeData = row;
      new this.$pageModal(
        selectPosition,
        {
          props: {
            propsPosintionInfo: {
              idx: idx,
              tenantCode: this.propsPosintionInfo.tenantCode
            }
          }
        },
        data => {
          if (data) {
            this.formInfo.jobName = data.name;
            this.formInfo.jobCode = data.code;
          }
        }
      );
    },
    // 切换模板
    changeSelect(val) {
      templateDetail(val).then(res => {
        this.ruleList = res.data.attributeContent.template;
        this.isShow = true;
      });
    }
  }
};
</script>
<style lang="less">
.cursor {
  cursor: pointer;
}
.ivu-form-item-content .ivu-input-with-search .ivu-input-search {
  background: #ff6f4b !important;
}
.ivu-form-item-content .ivu-input-with-search .ivu-input-search:hover {
  border: 1px solid #dcdee2 !important;
}
.extendedAttrTitle {
  font-size: 14px;
  font-weight: bold;
  border-bottom: 1px solid #f5f5f5;
  line-height: 40px;
  margin-bottom: 20px;
}
.select-btn {
  padding: 5px 23px !important;
}
</style>